<template>
  <div class="app-container">
    <div class="app-header">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['statistics:custom:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['statistics:custom:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['statistics:custom:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['statistics:custom:export']"
            >导出</el-button>
          </el-col>
      </el-row>

      <el-table
        v-loading="loading"
        :data="customList"
        @selection-change="handleSelectionChange"
        @cell-dblclick="handleDBCellClick"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="报表id" align="center" prop="id" width="80" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['statistics:custom:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['statistics:custom:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <div class="app-context">
        <el-form
          :model="queryCustomParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="100px"
        >
          <el-form-item label="工作单日期" prop="date">
            <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                unlink-panels
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
                </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      <el-table border :data="customResultList" height="700" style="overflow: auto">
        <div v-for="(item, index) in customTitleList" :key="index">
          <el-table-column :prop="item" align="center" :label="item">
            <template slot-scope="scope">
               {{  customResultList[scope.$index][index] }} 
            </template>
          </el-table-column>
        </div>
      </el-table>
    </div>

    <!-- 添加或修改自定义报表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="报表SQL" prop="sqlStr">
          <el-input
            v-model="form.sqlStr"
            type="textarea"
            placeholder="请输入合法的报表SQL语句"
            show-word-limit
            :autosize="{ minRows: 4, maxRows: 20 }"
            :style="{ width: '100%' }"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustom,
  getCustom,
  delCustom,
  addCustom,
  updateCustom,
  getCustomSql,
} from "@/api/assembly/custom";
import {listYield} from '@/api/assembly/statistics'
export default {
  name: "Custom",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      //自定义字段list
      customTitleList: [],
      customResultList: [],
      dateRange: [],
      // 总条数
      total: 0,
      // 自定义报表表格数据
      customList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      sqlStr: null,
      // 自定义报表的查询参数
      queryCustomParams: {
        pageNum: 1,
        pageSize: 10,
        sqlStr: null,
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sqlStr: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询自定义报表列表 */
    getList() {
      this.loading = true;
      listCustom(this.queryParams).then((response) => {
        this.customList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        sql: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getCustomSql();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加自定义报表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCustom(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改自定义报表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCustom(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustom(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDBCellClick(row) {
      this.queryCustomParams.sqlStr = row.sqlStr;
      this.sqlStr = row.sqlStr;
      this.getCustomSql();
    },
    getCustomSql(){
        let num = {};
        //console.log(this.addDateRange(num , this.dateRange))
        //listYield(this.addDateRange(num, this.dateRange));
        if(this.sqlStr != null){
            this.queryCustomParams.sqlStr =  this.sqlStr;
            if(this.dateRange!=null && this.dateRange.length > 0){
                if (this.queryCustomParams.sqlStr.toLowerCase().indexOf("where".toLowerCase())!= -1) {
                    this.queryCustomParams.sqlStr +=  " and create_time between '"+this.dateRange[0]+"' and '"+this.dateRange[1]+"'";
                }else{
                    this.queryCustomParams.sqlStr +=  " where create_time between '"+this.dateRange[0]+"' and '"+this.dateRange[1]+"'";
                }
            }
            getCustomSql(this.addDateRange(this.queryCustomParams, this.dateRange)).then((res) => {
              this.customTitleList = [];
              this.customResultList = [];
              if(res.data.title.length > 0){
                for(let i=0; i<res.data.title.length;i++){
                  this.customTitleList.push(res.data.title[i].value);
                }
                for(let i=0; i<res.data.value.length;i++){
                  this.customResultList.push(res.data.value[i].value);
                }
              }else{
                this.$modal.msgSuccess("数据不存在");
              }
            });
            }else{
                this.$modal.msgSuccess("请先双击选择报表");
            }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除自定义报表编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCustom(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "assembly/custom/export",
        {
          ...this.queryParams,
        },
        `custom_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped rel="stylesheet/scss" lang="scss">
.app-header {
  width: 25%;
  float: left;
}
.app-context {
  width: 73%;
  float: right;
}
</style>
